package com.jiuxian.scheduling.tasks;

import com.jiuxian.scheduling.util.SiteUtil;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.Vector;

/**
 * Created by wangjingqing on 2017/12/18.
 */
public class SchedulerApplication {

    static String group = "SCHEDULER";
    static Logger logger = LoggerFactory.getLogger(SchedulerApplication.class);

    static Scheduler scheduler = null;

    static{
        try {
            scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            logger.error("初始化scheduler失败：",e);
        }

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            if(scheduler != null){
                try {
                    scheduler.shutdown();
                } catch (SchedulerException e) {
                    logger.error("关闭scheduler失败：",e);
                }
            }
        }));
    }

    public static List<JobKey> keys = new Vector();

    private static boolean addKey(JobKey key){
        return keys.add(key);
    }

    public static boolean removeKey(JobKey key){
        return keys.remove(key);
    }

    /**
     * 是否包含当前任务<br>
     * @param name 任务名称<br>
     * @return boolean
     */
    public static boolean containJob(String name){
        return keys.contains(new JobKey(name,group));
    }

    /**
     * 添加任务<br>
     * @param schedingVO 任务信息
     */
    public static void addJob(SchedingVO schedingVO){
        try {
            //判断是否包含
            if(containJob(schedingVO.getName())){
                logger.info("任务已在执行中{}",schedingVO.getName());
                return;
            }
            Date nextDate = schedingVO.getNextDate() == null ? schedingVO.getNextDate().compareTo(new Date()) < 1? SiteUtil.getDate(schedingVO.getNextDate(),10):schedingVO.getNextDate():schedingVO.getNextDate();
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(schedingVO.getName(), group).withSchedule(CronScheduleBuilder.cronSchedule(schedingVO.getCron()))
                    .startAt(nextDate).build();
            JobDataMap data = new JobDataMap();
            data.put("schedingInfo",schedingVO);
            JobDetail job = JobBuilder.newJob(TaskJob.class).withIdentity(schedingVO.getName(),group).setJobData(data).build();
            addKey(job.getKey());
            scheduler.scheduleJob(job,trigger);
        } catch (SchedulerException e) {
            logger.error("添加任务失败：",e);
        }
    }

    /**
     * 移除任务根据name
     * @param name
     */
    public static boolean removeJob(String name){
        try {
            JobKey jobKey = new JobKey(name, group);
            removeKey(jobKey);
            return scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            logger.error("移除任务失败：",e);
        }
        return false;
    }

    /**
     * 暂停当前任务<br>
     * @param name 任务名称
     */
    public static boolean pauseJob(String name){
        try {
            scheduler.pauseJob(new JobKey(name,group));
            return true;
        } catch (Exception e) {
            logger.error("终端当前任务失败：",e);
        }
        return false;
    }

    /**
     * 重新唤起<br>
     * @param name
     * @return
     */
    public static boolean resumeJob(String name){
        try {
            scheduler.resumeJob(new JobKey(name,group));
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }
}
